package org.boot.fast.util;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.boot.fast.listener.FastExcelExportListener;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 通用导出Excel工具
 * @author: 最爱芫荽
 * @email: 15733440205@163.com
 */
@Slf4j
@SuppressWarnings("all")
public class ExcelExporterUtil {

    /**
     * 导出Excel，响应byte
     * @param list
     * @return
     */
    public static byte[] exportExcel(List<Map<String, Object>> list) {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("data");

        // 获取导出监听器Bean
        FastExcelExportListener bean = SpringUtil.getBean(FastExcelExportListener.class);

        // 创建表头
        if (!list.isEmpty()) {
            Map<String, Object> firstRow = list.get(0);
            Row headerRow = sheet.createRow(0);
            int columnIndex = 0;
            for (String key : firstRow.keySet()) {
                Cell cell = headerRow.createCell(columnIndex++);
                cell.setCellValue(key);
            }

            // 填充数据
            int rowIndex = 1;
            for (Map<String, Object> rowData : list) {
                Row dataRow = sheet.createRow(rowIndex++);
                columnIndex = 0;

                for (Map.Entry<String, Object> entry : rowData.entrySet()) {
                    Cell cell = dataRow.createCell(columnIndex++);
                    if (entry.getValue() != null) {
                        //填充行数据
                        //在这里处理数据翻译
                        Object value = entry.getValue();
                        try{
                            if(bean != null){
                                Object data = bean.cellExportProcess(entry.getKey(), value);
                                value = data != null ? data : value;
                            }
                        } catch (Exception e) {
                            //捕获异常，传递给导出监听器处理
                            if(bean != null){
                                bean.collExportErrorProcess(entry.getKey(), value, rowIndex, columnIndex, e);
                            }else{
                                throw new RuntimeException(e);
                            }
                        }finally {
                            cell.setCellValue(value != null ? value.toString() : null);
                        }
                    }
                }

            }
        }

        // 调整列宽
        for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
            sheet.autoSizeColumn(i);
        }

        // 将工作簿写入字节数组输出流以获取字节码
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            workbook.write(byteArrayOutputStream);
        } catch (IOException e) {
            log.error("将工作簿写入字节数组输出流时发生异常：", e);
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                log.error("关闭工作簿时发生异常：", e);
                e.printStackTrace();
            }
        }
        // 获取字节码数组
        return byteArrayOutputStream.toByteArray();
    }


    /**
     * 导出Excel，响应byte[]字节码数据
     * @param list
     * @param configJson
     * @return
     */
    public static byte[] exportExcel(List<Map<String, Object>> list, Map<String, Object> configJson) {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("data");

        // 获取导出监听器Bean
        FastExcelExportListener bean = SpringUtil.getBean(FastExcelExportListener.class);

        // 创建表头
        if (!list.isEmpty()) {
            // 转换数据表头
            List<Map<String, Object>> titleList = convert(list, configJson);

            Map<String, Object> firstRow = titleList.get(0);
            Row headerRow = sheet.createRow(0);
            int columnIndex = 0;
            for (String key : firstRow.keySet()) {
                Cell cell = headerRow.createCell(columnIndex++);
                cell.setCellValue(key);
            }

            // 填充数据
            int rowIndex = 1;
            for (Map<String, Object> rowData : list) {
                Row dataRow = sheet.createRow(rowIndex++);
                columnIndex = 0;

                for (Map.Entry<String, Object> entry : rowData.entrySet()) {
                    Cell cell = dataRow.createCell(columnIndex++);
                    if (entry.getValue() != null) {
                        //填充行数据
                        //在这里处理数据翻译
                        Object value = entry.getValue();
                        try{
                            if(bean != null){
                                Object data = bean.cellExportProcess(entry.getKey(), value);
                                value = data != null ? data : value;
                            }
                        } catch (Exception e) {
                            //捕获异常，传递给导出监听器处理
                            if(bean != null){
                                bean.collExportErrorProcess(entry.getKey(), value, rowIndex, columnIndex, e);
                            }else{
                                throw new RuntimeException(e);
                            }
                        }finally {
                            cell.setCellValue(value != null ? value.toString() : null);
                        }
                    }
                }


            }
        }

        // 调整列宽
        for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
            sheet.autoSizeColumn(i);
        }

        // 将工作簿写入字节数组输出流以获取字节码
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            workbook.write(byteArrayOutputStream);
        } catch (IOException e) {
            log.error("将工作簿写入字节数组输出流时发生异常：", e);
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                log.error("关闭工作簿时发生异常：", e);
                e.printStackTrace();
            }
        }
        // 获取字节码数组
        return byteArrayOutputStream.toByteArray();
    }

    private static List<Map<String, Object>> convert(List<Map<String, Object>> list, Map<String, Object> configJson){
        if (CollUtil.isEmpty(list) || CollUtil.isEmpty(configJson)){
            return list;
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Map<String, Object> data = new LinkedHashMap<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object obj = configJson.get(entry.getKey());
                if(obj != null) key = obj.toString();
                data.put(key, entry.getValue());
            }
            result.add(data);
        }
        return result;
    }









}
